package sdk.pay.service;


import android.accessibilityservice.AccessibilityService;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import sdk.pay.helper.PayAssistant;
import sdk.pay.utils.PayLogUtil;

import java.util.ArrayList;
import java.util.List;

import static sdk.pay.constant.PayConstant.ACTION_ACCESSIBILITYSERVICE;

/**
 * Description:
 * File: PayAccessibilityService.java
 * Author: Administrator
 * Create: 2018/11/17 0017 下午 16:41
 */
public class PayAccessibilityService extends AccessibilityService {
    private static final String ALI_PACKAGE_NAME = "com.eg.android.AlipayGphone";
    private static final String ALI_NOTICE_POP_DIALOG_NAME = "com.alipay.mobile.commonui.widget.APNoticePopDialog";
    private static final String ALI_PAYEE_QR_PAY_ACTIVITY_NAME = "com.alipay.mobile.payee.ui.PayeeQRPayFormActivity";
    private static final String ALI_PAY_ACTIVITY_NAME = "com.alipay.android.msp.ui.views.MspContainerActivity";
    private static final String ALI_TRANSFER_ACTIVITY_NAME = "com.alipay.mobile.transferapp.ui.TFToAccountConfirmActivity_";
    private static final String ALI_PACKAGE_LOGIN_IN = "com.eg.android.AlipayGphone.AlipayLogin";
    private static final String ALI_SCAN_QR_ACTIVITY_NAME = "com.alipay.mobile.scan.as.main.MainCaptureActivity";
    private Handler mHandler;
    private List<AccessibilityNodeInfo> accessibilityNodeInfoList;
    private static final int MSG_ENABLE_STATE = 0;
    private static final int MSG_DISABLE_STATE = 1;
    private int mIndex = 0;

    @Override
    public void onCreate() {
        super.onCreate();
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                int what = msg.what;
                switch (what) {
                    case MSG_ENABLE_STATE:
                        PayAssistant.setsCanUseState(true);
                        break;
                    case MSG_DISABLE_STATE:
                        PayAssistant.setsCanUseState(false);
                        mIndex = 0;
                        break;
                }
            }
        };
    }

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        CharSequence charSequence = event.getPackageName();
        if (TextUtils.isEmpty(charSequence)) {
            return;
        }
        String packageName = charSequence.toString();
        if (!TextUtils.isEmpty(packageName)) {
            if (ALI_PACKAGE_NAME.equals(packageName) && PayAssistant.getCanUseState() && PayAssistant.getNeedSet()) {
                String className = event.getClassName().toString();
                switch (className) {
                    case ALI_PAY_ACTIVITY_NAME:
                    case ALI_PAYEE_QR_PAY_ACTIVITY_NAME:
//                    case ALI_TRANSFER_ACTIVITY_NAME:
                        mIndex++;
                        doSetPayValue(PayAssistant.getMoney(), PayAssistant.getRemark());
                        break;
                    case ALI_SCAN_QR_ACTIVITY_NAME:
                        clickBackBtn();
                        break;
                    case ALI_NOTICE_POP_DIALOG_NAME:
                        clickCancelDialog();
                        break;
                    default:
                        break;
                }
            } else if (ALI_PACKAGE_NAME.equals(packageName)) {
                String name = event.getClassName().toString();
                if (!TextUtils.isEmpty(name)) {
                    if (ALI_PACKAGE_LOGIN_IN.equals(name)) {
                        mIndex = 0;
                    }
                }
            }
        }
    }

    private void clickBackBtn() {
        if (mIndex > 0) {
            mIndex = 0;
        } else {
            Intent intent = new Intent(ACTION_ACCESSIBILITYSERVICE);
            LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
        }
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        List<AccessibilityNodeInfo> list = getRootInActiveWindow().
                findAccessibilityNodeInfosByViewId("com.alipay.mobile.scan:id/titleBar_back");
        if (null != list && list.size() > 0) {
            list.get(0).performAction(AccessibilityNodeInfo.ACTION_CLICK);
        } else {
            list = getRootInActiveWindow().
                    findAccessibilityNodeInfosByViewId("com.alipay.mobile.scan:id/title_bar_back");
            if (null != list && list.size() > 0) {
                list.get(0).performAction(AccessibilityNodeInfo.ACTION_CLICK);
            }
        }
        mIndex = 0;
    }

    @Override
    public void onInterrupt() {

    }

    private void doSetPayValue(final String money, final String remark) {
        PayLogUtil.logBase("doSetPayValue mIndex = " + mIndex);
        if (mIndex == 1) {
            mHandler.sendEmptyMessage(MSG_ENABLE_STATE);
            PayLogUtil.logBase("doSetPayValue money = " + money + " remark = " + remark);
            try {
                Thread.sleep(200);
                PayLogUtil.logBase("doSetPayValue");
                AccessibilityNodeInfo info = getRootInActiveWindow();
                List<AccessibilityNodeInfo> list = info.findAccessibilityNodeInfosByText("知道了");
                if (null != list && list.size() > 0) {
                    list.get(0).performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    Thread.sleep(200);
                    info = getRootInActiveWindow();
                }
                list = info.findAccessibilityNodeInfosByText("付款金额");
                if (null != list && list.size() > 0) {
                    AccessibilityNodeInfo targetInfo = list.get(0).getParent();
                    accessibilityNodeInfoList = new ArrayList<>();
                    setMoneyAndRemark(targetInfo, money, remark);
                } else {
                    list = info.findAccessibilityNodeInfosByText("转账金额");
                    if (null != list && list.size() > 0) {
                        AccessibilityNodeInfo targetInfo = list.get(0).getParent();
                        accessibilityNodeInfoList = new ArrayList<>();
                        setMoneyAndRemark(targetInfo, money, remark);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                PayLogUtil.logBase("doSetPayValue Exception e : " + e.toString());
            } finally {
                mHandler.sendEmptyMessage(MSG_DISABLE_STATE);
            }
        }
    }

    //设置金额和备注，然后付款
    private void setMoneyAndRemark(final AccessibilityNodeInfo targetInfo, final String money, final String remark) {
        PayLogUtil.logBase("setMoneyAndRemark money = " + money + " remark = " + remark);
        if (null == targetInfo) {
            return;
        }
        for (int i = 0; i < targetInfo.getChildCount(); i++) {
            String className = String.valueOf(targetInfo.getChild(i).getClassName());
            if (className.endsWith("EditText")) {
                accessibilityNodeInfoList.add(targetInfo.getChild(i));
            } else if (className.endsWith("Layout") || className.endsWith("View")) {
                setMoneyAndRemark(targetInfo.getChild(i), money, remark);
            }
        }
        if (accessibilityNodeInfoList.size() >= 2) {
            setContent(accessibilityNodeInfoList.get(0), money);
            setContent(accessibilityNodeInfoList.get(1), remark);
        }
    }

    /**
     * click personal account dialog
     */
    private void clickCancelDialog() {
        try {
            Thread.sleep(200);
            AccessibilityNodeInfo info = getRootInActiveWindow();
            List<AccessibilityNodeInfo> list = info.findAccessibilityNodeInfosByText("知道了");
            if (null == list && list.size() > 0) {
                list.get(0).performAction(AccessibilityNodeInfo.ACTION_CLICK);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void setContent(AccessibilityNodeInfo info, String content) {
        if (info == null) {
            return;
        }
        Bundle arguments = new Bundle();
        arguments.putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, content);
        info.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, arguments);
    }
}
